from odoo import fields, models, api
from odoo.exceptions import UserError
from ...functions.rp_sequence_code_fc import RPSequenceCode

ERROR_TYPE = [('other', 'other'), ('user', 'user'), ('onchange', 'onchange'), ('depends', 'depends'), ('constrains', 'constrains'), ('orm', 'ORM'), ('sql', 'SQL'), ('selection', 'selection')]
ERROR_TYPE_PRE = {'other': 'OT', 'user': 'US', 'onchange': 'OC', 'depends': 'DP', 'constrains': 'CT', 'orm': 'ORM', 'sql': 'SQL', 'selection': 'SL'}


class RPErrorJson(models.Model):
    _name = 'rp.error.json'
    _description = "操作错误json"
    _rec_name = "code"
    _sql_constraints = [('unique_name', 'UNIQUE(code)', '编码不能重复')]

    code = fields.Char(string='编码', index=True, copy=False, required=True)
    type = fields.Selection(string='错误类型', selection=ERROR_TYPE, default=ERROR_TYPE[0][0])
    desc = fields.Char(string='描述')
    active = fields.Boolean(string='有效', default=True)

    def create(self, vals):
        prefix = ERROR_TYPE_PRE[vals.get('type')]
        code = RPSequenceCode(self.env).explore_sequence(model=self._name, prefix=prefix, key='ER', padding=4)
        vals.update({'code': code})
        return super(RPErrorJson, self).create(vals)
